package com.abe.libquick.utils.quick;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;

import androidx.core.app.ActivityCompat;


import com.abe.libcore.utils.ExternalFileUtils;
import com.abe.libquick.utils.NormalUtils;

import java.io.File;
import java.util.UUID;

public class AppUtils {

    /**
     * 获取imei号
     */
    @SuppressLint({"HardwareIds", "MissingPermission"})
    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            return generateDeviceId();
        }
        String imei = telephonyManager.getDeviceId();
        //预防取不到IMEI，生成一个随机并缓存，如清理掉需重新生成
        if (TextUtils.isEmpty(imei)) {
            imei = generateDeviceId();
        }
        return imei;
    }

    private static String generateDeviceId() {
        String filePath = ExternalFileUtils.INSTANCE.fileRootPath() + File.separator + "main.txt";
        //则生成一个id：随机码
        String UUID64 = NormalUtils.getFileInfo(filePath);
        String uuid;
        if (UUID64 == null || UUID64.equals("")) {
            uuid = UUID.randomUUID().toString();
            UUID64 = Base64.encodeToString(uuid.getBytes(), Base64.DEFAULT);
            NormalUtils.saveFileInfo(filePath, UUID64);
        } else {
            uuid = new String(Base64.decode(UUID64.getBytes(), Base64.DEFAULT));
        }
        return uuid;
    }

    /**
     * 获取手机号
     */
    @SuppressLint({"HardwareIds", "MissingPermission"})
    public static String getTEL(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            return "";
        }
        return telephonyManager.getLine1Number();
    }
}